package com.eh.proxy.authority;

import com.eh.proxy.authority.handler.NonOwnerInvocationHandler;
import com.eh.proxy.authority.handler.OwnerInvocationHandler;
import com.eh.proxy.authority.model.PersonBean;
import com.eh.proxy.authority.model.impl.PersonBeanImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * Created by David on 2016/5/3.
 */
public class AuthorityDriveTest {
    public static void main(String[] args) {
        PersonBean personBean = new PersonBeanImpl("壮壮", "男", "篮球");
        for (int i = 0; i < 10; i++) {
            PersonBean nonOwnerProxy = getNonOwnerProxy(personBean);
            nonOwnerProxy.setHotOrNotRating(Math.random() > 0.5 ? 1 : 0);
        }
        try {
            PersonBean nonOwnerProxy = getNonOwnerProxy(personBean);
            nonOwnerProxy.setName("红红");
        } catch (Exception e) {
            System.out.println("没有权限给别人设置信息");
        }

        PersonBean ownerPersonBean = getOwnerProxy(personBean);
        System.out.println("大家对我的喜爱度： " + ownerPersonBean.getHotOrNotRating());
        try {
            ownerPersonBean.setHotOrNotRating(1);
        } catch (Exception e) {
            System.out.println("没有权限给自己增加喜爱度");
        }
    }

    private static PersonBean getOwnerProxy(PersonBean personBean) {
        return getProxy(personBean, new OwnerInvocationHandler(personBean));
    }

    private static PersonBean getNonOwnerProxy(PersonBean personBean) {
        return getProxy(personBean, new NonOwnerInvocationHandler(personBean));
    }

    private static PersonBean getProxy(PersonBean personBean, InvocationHandler invocationHandler) {
        return (PersonBean) Proxy
                .newProxyInstance(personBean.getClass().getClassLoader(), personBean.getClass().getInterfaces(), invocationHandler);
    }
}
